package com.molange.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.molange.behavior.mapper.LikeBehaviorMapper;
import com.molange.behavior.mapper.UserRealtionMapper;
import com.molange.behavior.service.FavouriteService;
import com.molange.behavior.service.RelationService;
import com.molange.model.behavior.pojos.LikeBehavior;
import com.molange.model.behavior.pojos.UserRealtion;
import com.molange.model.common.ResponseResult;
import com.molange.utils.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author wangshiqi
 * @version 1.0
 * @date 2023/2/26 10:02
 */
@Service
@Slf4j
public class UserRelationServiceImpl extends ServiceImpl<UserRealtionMapper, UserRealtion>
        implements RelationService {

    @Autowired
    private RelationService relationService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 用户关注行为服务
     *
     * @param token      鉴权
     * @param userId     关注用户id
     * @param actionType 类型 1关注 2取消
     * @return
     */
    @Override
    public ResponseResult savaUserRelation(String token, String userId, String actionType) {
        log.info("开始保存用户关注信息");
        //有token,判断token是否有效
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        Integer tokenUserId = (Integer) claimsBody.get("id");
        log.info("这是用户中的id" + tokenUserId);
        if (null == userId || null == tokenUserId) {
            return new ResponseResult(100, "参数传递错误");
        }
        if (tokenUserId.toString().equals(userId)){
            return new ResponseResult(100,"你不能关注自己");
        }
        //用户关注
        if (StringUtils.isNotBlank(actionType) || "1".equals(actionType)) {
            UserRealtion userRealtion = new UserRealtion();
            userRealtion.setUserId(tokenUserId);//本人账号
            userRealtion.setRelationId(Integer.parseInt(userId));//关注人的id
            userRealtion.setCreateTime(new Date()); //关注时间
            //判断是否是相互关注
            userRealtion.setRelationTwo(0);
            save(userRealtion);
            Boolean relationTwo = relationService.isRelationTwo(tokenUserId, userId);
            Integer isRelation = (relationTwo == true ? 1 : 0);
            //保存后发现相互关注
            if (relationTwo){
                //相互关注了,设置相互关注状态
                setTwoUserRelationTwo(tokenUserId,userId);
            }
            //添加关注人数
            rabbitTemplate.convertAndSend("tiktok.topic", "behavior.addUserFollowCount", tokenUserId);
            //添加粉丝人数
            rabbitTemplate.convertAndSend("tiktok.topic", "behavior.addUserFollowerCount", Integer.parseInt(userId));

            return new ResponseResult(0, "用户关注成功！");
        }
        //取消关注
        if (StringUtils.isNotBlank(actionType) || "2".equals(actionType)) {
            //获取用户的关注信息，先判断是否关注过
            Boolean userRelationOther = isUserRelationOther(tokenUserId, userId);
            //没有关注过
            if (!userRelationOther) {
                return new ResponseResult(100, "未关注当前用户！");
            }
            //判断是否是相互关注
            Boolean relationTwo = isRelationTwo(tokenUserId, userId);
            if (relationTwo){
                //相互关注了，取消相互关注状态
                deleteTwoUserRelationTwo(tokenUserId,userId);
            }
            //关注了，开始取消关注
            LambdaQueryWrapper<UserRealtion> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(UserRealtion::getUserId, tokenUserId);
            queryWrapper.eq(UserRealtion::getRelationId, userId);
            //删除关注信息
            boolean remove = remove(queryWrapper);
            //删除了
            if (remove) {
                //开始修改用户的关注人数
                rabbitTemplate.convertAndSend("tiktok.topic", "behavior.deleteUserFollowCount", tokenUserId);
                //删除关注用户的粉丝数
                rabbitTemplate.convertAndSend("tiktok.topic", "behavior.deleteUserFollowerCount", Integer.parseInt(userId));
                return new ResponseResult(0, "取消关注成功");
            }
            //没有删除
            return new ResponseResult(100, "内部服务器错误");
        }
        return new ResponseResult(100, "参数请求错误");
    }


    /**
     * 设置用户为相互关注
     * @param tokenUserId 操作人id
     * @param userId 关注人id
     */
    @Override
    public void setTwoUserRelationTwo(Integer tokenUserId, String userId) {
        //更改存操作人状态
        LambdaQueryWrapper<UserRealtion> queryWrapper=new LambdaQueryWrapper();
        queryWrapper.eq(UserRealtion::getUserId,tokenUserId);
        queryWrapper.eq(UserRealtion::getRelationId,userId);
        UserRealtion one = getOne(queryWrapper);
        one.setRelationTwo(1);
        saveOrUpdate(one);
        LambdaQueryWrapper<UserRealtion> queryWrapper01=new LambdaQueryWrapper();
        queryWrapper01.eq(UserRealtion::getUserId,userId);
        queryWrapper01.eq(UserRealtion::getRelationId,tokenUserId);
        UserRealtion one1 = getOne(queryWrapper01);
        one1.setRelationTwo(1);
        saveOrUpdate(one1);
    }

    /**
     * 取消相互关注状态
     * @param tokenUserId 操作人id
     * @param userId 关注人id
     */
    @Override
    public void deleteTwoUserRelationTwo(Integer tokenUserId, String userId) {
        //更改存操作人状态
        LambdaQueryWrapper<UserRealtion> queryWrapper=new LambdaQueryWrapper();
        queryWrapper.eq(UserRealtion::getUserId,tokenUserId);
        queryWrapper.eq(UserRealtion::getRelationId,userId);
        UserRealtion one = getOne(queryWrapper);
        one.setRelationTwo(0);
        saveOrUpdate(one);
        LambdaQueryWrapper<UserRealtion> queryWrapper01=new LambdaQueryWrapper();
        queryWrapper01.eq(UserRealtion::getUserId,userId);
        queryWrapper01.eq(UserRealtion::getRelationId,tokenUserId);
        UserRealtion one1 = getOne(queryWrapper01);
        one1.setRelationTwo(0);
        saveOrUpdate(one1);
    }

    /**
     * 判断两个用户是否相互关注
     *
     * @param tokenUserId 操作人id
     * @param userId      关注人id
     * @return 是否相互关注 1表示相互关注 0表示不是相互关注
     */
    @Override
    public Boolean isRelationTwo(Integer tokenUserId, String userId) {
        if (null == tokenUserId || StringUtils.isBlank(userId)) {
            return false;
        }
        //可以进行下一步逻辑判断
        LambdaQueryWrapper<UserRealtion> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(UserRealtion::getUserId, tokenUserId);
        queryWrapper.eq(UserRealtion::getRelationId, userId);
        UserRealtion one = getOne(queryWrapper);
        LambdaQueryWrapper<UserRealtion> queryWrapper1 = new LambdaQueryWrapper();
        queryWrapper1.eq(UserRealtion::getUserId, userId);
        queryWrapper1.eq(UserRealtion::getRelationTwo, tokenUserId);
        UserRealtion one1 = getOne(queryWrapper1);
        if (null != one && null != one1) {
            return true;
        }
        return false;
    }

    /**
     * 是否单项关注
     * @param tokenUserId
     * @param userid
     * @return
     */
    @Override
    public Boolean isUserRelationOther(Integer tokenUserId, String userid) {
        //判断tokenuserId是否关注了userid
        LambdaQueryWrapper<UserRealtion> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(UserRealtion::getUserId, tokenUserId);
        queryWrapper.eq(UserRealtion::getRelationId, userid);
        UserRealtion one = getOne(queryWrapper);
        if (null == one) {
            return false;
        }
        return true;
    }
}
